package netty.dubborpc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class NettyServer {
    public static void startServer(String hostname,int port){
        startServer0(hostname, port);
    }

    private static void startServer0(String hostname,int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);  //指定一个线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建 服务器端的启动的对象 , 配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //设置
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 给 pipline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new NettyServerHandler());
                        }
                    });  //给workerGroup 的 EventLoop 设置处理区

            System.out.println("服务器 is ready ....");

            // 绑定一个端口 并且同步处理 , 启动
            ChannelFuture cf = bootstrap.bind(hostname, port).sync();

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
